//
//  TTPictureCollection.swift
//  WeiBo
//
//  Created by 涂永江 on 2017/6/10.
//  Copyright © 2017年 涂永江. All rights reserved.
//

import UIKit
import SDWebImage

//每一项的间距
let itemMagin = 5
//设置图片对象的宽度
let cellWidth = (screnssWidth - CGFloat(2*magin) - CGFloat(2*itemMagin))/3


class TTPictureCollection: UICollectionView {

    var pics:[TTPictureModel]?
    {
        didSet{
        
          lablea.text = "\(pics?.count ?? 0)"
            guard let picsM = pics else {
                return
            }
           
            setColltionViewSize(count: picsM.count)
            reloadData()
        }
    
    
    }
    
//   private var flowLaout :UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    private lazy var lablea :UILabel = {
    let label = UILabel(fontSize: 16, textColor: UIColor.red)
        
        return label
    
    }()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        // MARK:  --设置flowlaout
        let flowLaout = UICollectionViewFlowLayout()
        flowLaout.itemSize = CGSize(width: cellWidth, height: cellWidth)
        flowLaout.minimumLineSpacing = CGFloat(itemMagin)
        flowLaout.minimumInteritemSpacing = CGFloat(itemMagin)
       
        
        super.init(frame: frame, collectionViewLayout: flowLaout)
        
        
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    func setUI()
    {
        
        addSubview(lablea)
        lablea.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
        backgroundColor = UIColor.white
        
        dataSource = self as UICollectionViewDataSource
        
        register(TTHomePictureViewCell.self, forCellWithReuseIdentifier: retweetCellIdefier)
        
    }
    
    //设置colltionview的大小
    func setColltionViewSize(count:Int)
    {
        if count == 1 {
            
            let imageUrl = pics?.first?.thumbnail_pic
            
            //根据url取出图片
            
            if let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: imageUrl)
            {
                var sizeImage = image.size
                
                if sizeImage.width < 80
                {
                    let currentW:CGFloat = 80
                    
                    var  cutrrenH = CGFloat(currentW) / sizeImage.width * sizeImage.height
                    
                    
                    if cutrrenH > 150
                    {
                        cutrrenH = 150
                    }
                    sizeImage = CGSize(width: currentW, height: cutrrenH)
                }
                //更新约束
                self.snp.updateConstraints({ (make) in
                    make.size.equalTo(sizeImage).priority(.high)
                })
                
                //重新设item大小
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = sizeImage
                
                //结束
                return
            }
            
        }
        
        //多少列
        let lie = count > 3 ? 3:count
        //多少行
        let row = (count-1)/3 + 1
        
        //根据多少列和行求colltionview宽的距离
        
        let colltionViewWidth = CGFloat(lie) * cellWidth + CGFloat((lie-1)) * CGFloat(itemMagin)
        
        //根据多少列和行求colltionview高的距离
        let colltionViewHeight = CGFloat(row) * cellWidth + CGFloat((row-1)) * CGFloat(itemMagin)
        
        //更新colltionView 的约束
        self.snp.updateConstraints { (make) in
            make.size.equalTo(CGSize(width: colltionViewWidth, height: colltionViewHeight)).priority(.high)
            
        }
        
        //重新设item大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: cellWidth, height: cellWidth)
        
    }
    
}

// MARK:  --数据源

extension TTPictureCollection:UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pics?.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: retweetCellIdefier, for: indexPath) as! TTHomePictureViewCell
        cell.backgroundColor = UIColor.red
        cell.thumbnail_pic = pics?[indexPath.item]
        return cell
        
    }
    
    }
    
  // MARK:  --自定义cell
class TTHomePictureViewCell: UICollectionViewCell
{
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var thumbnail_pic:TTPictureModel?
    {
        didSet
        {
            
            if let url = thumbnail_pic?.thumbnail_pic{
                putureImage.sd_setImage(with: URL(string:url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
            
        }
    }
    //懒加载UIimageView
    private let putureImage:UIImageView = {
        let putureImagee =  UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        
        putureImagee.contentMode = .scaleAspectFill
        putureImagee.clipsToBounds = true
        
        return putureImagee
    }()
    
    //设置子控件
    func setUI()
    {
        contentView.addSubview(putureImage)
        putureImage.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
    }
}



